package cn.meng.base.handler;

import cn.hutool.core.date.DateTime;
import cn.meng.base.service.EmployeeService;
import cn.meng.base.utils.GenerateUtil;
import cn.meng.base.vo.BusinessException;
import cn.meng.base.vo.EmployeeVo;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 员工信息导入监听器
 * @author 万梦辉
 */
public class EmployeeExcelImportListener extends AnalysisEventListener<EmployeeVo> {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 每隔500条存储数据库，然后清理list,方便内存回收
     */
    private static final Integer BATCH_COUNT = 20000;

    List<EmployeeVo> list = new ArrayList<>();

    private EmployeeService employeeService;

    public EmployeeExcelImportListener(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    /**
     *  这个每一条数据解析都会来调用
     * @param employeeVo
     * @param analysisContext
     */
    @Override
    public void invoke(EmployeeVo employeeVo, AnalysisContext analysisContext) {
        log.info("开始解析数据......");
        try {
            String pk_employee = GenerateUtil.getInstance().generate();
            employeeVo.setPkEmployee(pk_employee);
            employeeVo.setDr(0);
            employeeVo.setTs(new DateTime());
            list.add(employeeVo);
            if(list.size() > BATCH_COUNT) {
                log.info("数据量超过了限制、进行批量增加");
                save();
                list.clear();
                log.info("数据保存成功");
            }
        } catch (BusinessException e) {
            log.error(e.getMessage());
        }
    }

    /**
     *  所有数据解析完成了 才会来调用
     *  在这里再写一次save是为了当数据量不足BATCH_COUNT的时候，也进行数据保存
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        save();
    }

    private Integer save() {
        log.info("开始保存数据......");
        Integer result = null;
        try {
            result = employeeService.batchInsertEmployee(list);
            log.info("成功插入 " + result + " 条数据");
        } catch (Exception e) {
            log.error("数据保存出现异常");
            e.printStackTrace();
        }
        return result;
    }
}
